const { log } = require('console');
const express = require('express');
const router = express.Router();
const urlLib = require('url');

router.use(function (req, res, next) {
  if (req.url == '/favicon.ico') {
    res.end('404');
    return;
  }

  try {
    let myobj = urlLib.parse(req.url, true);
    let name = myobj.pathname;

    // Option请求需要放行200
    if(req.method == "OPTIONS"){
      res.send(200);
    }

    let UrlArr = name.split('/');
    let controllerName = UrlArr[1] ? UrlArr[1] : 'index';
    let actionName = UrlArr[2] ? UrlArr[2] : 'index';

    actionName = req.method.toLowerCase() + '_' + actionName;
  
    controllerName = controllerName[0].toUpperCase() + controllerName.substr(1);
    req.actionName = actionName;
    req.controllerName = controllerName;
    console.log(`${req.method.toUpperCase()} : ${controllerName}/${req.actionName}`);
    const controllerObj = require(`../app/${req.moduleName}/controllers/${controllerName}Controller`);
    controllerObj[actionName](req, res, next);
  } catch (err) {
    throw err;
  }
})

module.exports = router;
